package cn.JHai.controller;

import cn.JHai.dao.MusicDao;
import cn.JHai.domain.Music;
import cn.JHai.service.impl.MusicServiceImp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

@Controller
@RequestMapping("/music")
public class MusciController {

    @Autowired
    MusicServiceImp musicServiceImp;

    //下载音乐
    @RequestMapping("download")
    public void download(String name, HttpSession session, HttpServletResponse response, HttpServletRequest request) throws IOException {

        /*System.out.println(outpath);*/
        //下载文件：需要设置 消息头
        response.setCharacterEncoding("utf-8");
        response.addHeader("content-Type","application/octet-stream" );//MIME类型:二进制文件（任意文件）
        response.addHeader("content-Disposition","attachement;filename="+name);//fileName包含了文件后缀：abc.txt
        String root= (String) session.getAttribute("root");
        ArrayList<Music> musicArrayList = musicServiceImp.findmusic(name);
        if ((musicArrayList != null) && musicArrayList.get(0)!=null) {
            Music music = musicArrayList.get(0);
            InputStream in = request.getServletContext().getResourceAsStream("/"+music.getSrc().trim()) ;
            ServletOutputStream out = response.getOutputStream() ;
            byte[] bs = new byte[10];
            int len=-1 ;
            while(  (len=in.read(bs)) != -1) {
                out.write(bs,0,len);
            }
            out.close();
            in.close();
            response.getWriter().write("true");
        }
            response.getWriter().write("false");
    }

    //查找音乐
    @RequestMapping("seach")
    public void search(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");
        String search = request.getParameter("search");
        HttpSession session = request.getSession();
        ArrayList<Music> findmusic = musicServiceImp.findmusic(search);
        request.setAttribute("findmusic", findmusic);
        session.setAttribute("count", 1);
        System.out.println("ok");
        request.getRequestDispatcher("/search.jsp").forward(request, response);
    }


}
